<?php
 namespace app\dao;
 /**
  * @desc 销售退货明细操作类
  */
 
 use yii\db\Query;
 use app\enum\EnumOther;
 use Yii;
 use app\dao\BaseDAO;
 
 class SaleReturnDetailDAO extends BaseDAO 
 {
 	/**
 	 * @desc 构造函数
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function __construct()
 	{
 		parent::__construct();
 		$this->_table = 'salereturn_detail';
 		$this->_pKey ='salereturn_det_id';
 	}
 	
 	/**
 	 * @inheritdoc
 	 */
 	public static function tableName()
 	{
 		return '{{%salereturn_detail}}';
 	}
 	
 	/**
 	 * @desc 根据id 获取销售退货单明细
 	 * @param $id 退货单id
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function getSaleReturnDet($id)
 	{
 		$selects = "salereturn_det_id,d.salereturn_id,d.product_id,d.quantity,d.remark,p.product_name,product_sn,s.warehouse_id,saleout_det_id,base_price,
				d.quantity_unit,d.price,d.amount,d.discount,base_quantity,base_unit,u.unit_name base_name,second_quantity,second_unit,second_relation,p.unit_content";
 		$conditions ="d.salereturn_id = :id and d.delete_flag = :flag";
 		$params = [
 				':id'=>$id,
 				':flag'=>EnumOther::NO_DELETE,
 		];
 		$query = new Query();
 		$result = $query->select($selects)
 		->from("$this->_table d")
 		->leftJoin("product p",'d.product_id = p.product_id')
 		->leftJoin("unit u","u.unit_id = d.base_unit")
 		->leftJoin("salereturn s","s.salereturn_id = d.salereturn_id")
 		->where($conditions,$params)
 		->all();
 		foreach ($result as &$res){
 			$res_units = ProductUnitDAO::getInstance()->getUnits($res['product_id'] );
 			$res['product_unit'] = $res_units;
 			$res_quantity = StockPileDAO::getInstance()->findByAttributes('quantity','product_id = :pid and warehouse_id =:wid',[':pid'=>$res['product_id'],':wid'=>$res['warehouse_id']]);
 			$res['product_quantity'] = isset($res_quantity['quantity']) ? $res_quantity['quantity']:0;
 		}
 		return $result;
 	
 	}
 }
